import axios from "axios";
// import store from '@/store'
// import { ElMessage } from 'element-ui'
import { getCookie, TokenKey } from "@/utils/Cookie";

// axios.defaults.withCredentials = true
// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 50000, // 请求超时时间
  withCredentials: true,
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    // if (store.getters.token) {
    config.headers[TokenKey] = getCookie(TokenKey);
    // console.log(config)
    // }
    return config;
  },
  (error) => {
    // Do something with request error
    // console.log(error) // for debug
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  (response) => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    const res = response;
    if (!res.success) {
      // 401:Token 过期了;
      if (res.code === 401) {
        window.location.href =
          process.env.VUE_APP_LOGIN_PATH + window.location.href;
        return false;
      } else {
      }

      // if (res.code === 403) {
      //   ElMessage({
      //     type: 'warning',
      //     message: msg || '抱歉，您无权限访问该页面'
      //   })
      // }

      return Promise.resolve(response);
    } else {
      return response.data;
    }
  },
  (error) => {
    if (error.response.status === 401) {
      window.location.href =
        process.env.VUE_APP_LOGIN_PATH + window.location.href;
    }
    return Promise.reject(error);
  }
);

export default service;
